package config

import (
	"errors"
	"strings"

	"gitee.com/xiaoyutab/xgotool/individual/xgorm"
	"github.com/glebarez/sqlite"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var roots *gorm.DB

// 获取根日志数据库连接
func GetConnect() (*xgorm.XDB, error) {
	if config == nil {
		GetDefault()
	}
	var err error
	if roots == nil {
		switch getType(config.DSN) {
		case "mysql":
			roots, err = gorm.Open(mysql.Open(config.DSN), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
		case "sqlite":
			roots, err = gorm.Open(sqlite.Open(config.DSN), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
		default:
			err = errors.New("暂不支持此数据库连接")
		}
		if err == nil {
			// 第一次连接数据库的话，自动创建对应数据表
			autoDatabases()
		}
	}
	return xgorm.To(roots), err
}

// 获取数据库连接类型
//
//	dsn	驱动DSN连接字符串
func getType(dsn string) string {
	if strings.Contains(dsn, ".db") || dsn == ":memory:" || strings.Contains(dsn, ".sqlite") {
		return "sqlite"
	} else if strings.Contains(dsn, " user=") || strings.Contains(dsn, "postgres://") {
		return "postgres"
	} else if strings.Contains(dsn, "sqlserver://") || strings.Contains(dsn, "user id=") {
		return "sqlserver"
	}
	return "mysql"
}
